package main

import (
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

type ListFile struct {
	Name  string
	Size  int64
	IsDir bool
	Depth int
	Path  string
}

func ExistFile(filename string) bool {
	d, err := os.Stat(filename)
	if err == nil || os.IsExist(err) {
		if d.IsDir() {
			return false
		}
		return true
	}
	return false
}

// 检查文件或目录是否存在
// 如果由 filename 指定的文件或目录存在则返回 true，否则返回 false
func ExistMd(filename string) bool {
	filename = conf.MdPath + filename
	log.Println(filename)
	d, err := os.Stat(filename)
	if err == nil || os.IsExist(err) {
		if d.IsDir() {
			return false
		}
		return true
	}
	return false
}

// 获取目录
func doHashWalk(dirPath string) ([]ListFile, error) {

	var ListPath []ListFile

	fullpath, err := filepath.Abs(dirPath)

	if err != nil {
		return ListPath, err
	}

	callback := func(path string, fi os.FileInfo, err error) error {
		// return hashFile(fullpath, path, fi, err)
		// var rex = regexp.MustCompile(`([.]*).md`)
		var rex = regexp.MustCompile(`\.git|\.[^md]`)
		Rel, err := filepath.Rel(fullpath, path)
		Rel = strings.Replace(Rel, "\\", "/", -1)
		if err == nil && !rex.MatchString(Rel) {
			ListPath = append(ListPath, ListFile{
				Name:  fi.Name(),
				Size:  fi.Size(),
				IsDir: fi.IsDir(),
				Depth: strings.Count(Rel, "/"),
				Path:  Rel,
			})
		}

		return nil
	}

	filepath.Walk(fullpath, callback)

	return ListPath, nil
}

func mkDirs(filePath string) error {
	lDir := conf.MdPath + filepath.Dir(filePath)
	ok, err := os.Stat(lDir)

	if err != nil || !ok.IsDir() {
		log.Println(err.Error())
		err = os.Mkdir(lDir, 0755)
		if err != nil {
			log.Println(err.Error())
		}
	}

	return err
}
